package com.acooly.module.openapi.client.provider.fuyou.security;

import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.provider.fuyou.FuyouConstants;
import com.acooly.module.safety.exception.SignatureVerifyException;
import com.acooly.module.safety.signature.Signer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;

/**
 * @author zhike 2017/11/28 11:41
 */
@Component("safetyFuyouMd5Signer")
@Slf4j
public class FuyouMd5Signer implements Signer<String, String> {

    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };


    @Override
    public String sign(String plain, String key) {
        String watForSign = plain;
        watForSign =watForSign.trim();
        String resultString;
        try {
            resultString = new String(watForSign);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString
                    .getBytes("UTF-8")));
        } catch (Exception ex) {
            log.info("签名失败：{}", ex.getMessage());
            throw new ApiClientException("签名失败:"+ex.getMessage());
        }
        return resultString;
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    @Override
    public void verify(String plain, String key, String verifySign) {
        // MD5摘要签名计算
        String signature = sign(plain,key);
        if (!verifySign.equalsIgnoreCase(signature)) {
            throw new SignatureVerifyException("验签未通过");
        }
    }

    @Override
    public String getSinType() {
        return FuyouConstants.MD5_SIGN_TYPE;
    }
}




